<?php
/**
 * Created by PhpStorm.
 * User: 张华杰
 * Date: 10/30/17
 * Time: 2:38 PM
 */
namespace app\models;

use Yii;
use yii\base\Model;

class AdminLoginForm extends Model
{
    public $username;
    public $password;
    public $rememberMe = true;
    private $_user = false;

    /**
     * @return array the validation rules.
     */
    public function rules()
    {
        return [
            [['username'], 'trim'],
            [['username'], 'required', 'message' => '帐号名不能为空'],
            [['password'], 'required', 'message' => '密码不能为空'],

        ];
    }

    /**
     * @inheritdoc
     */
    public function attribute()
    {
        return [
            'username' => '用户名',
            'password' => '密码',
            'rememberMe' => '记住我',
        ];
    }


    public function login()
    {
        if (!$this->hasErrors()) {
            $user = $this->getUser();
            if (!$user || !$user->validatePassword($this->password)) {
                $this->addError('password', '密码错误');
                return false;
            }
            return Yii::$app->user->login($this->getUser(),  $this->rememberMe ? 3600 * 24 * 7 : 0 );
        }
        return false;
    }

    /**
     * 功能：根据用户名获取user
     *
     * Created by 张华杰.
     * email: blues@lonlife.cn
     */
    public function getUser()
    {
        if ($this->_user === false) {
            $this->_user = AdminUserIdentity::findByUsername($this->username);
        }
        return $this->_user;
    }

}
